/*
 * @Author: 圆月豌豆 232957726@qq.com
 * @Date: 2025-08-20 14:18:01
 * @LastEditors: Teemor
 * @LastEditTime: 2025-09-08 14:15:04
 * @FilePath: \3DthreeEdit\src\store\modules\packagesStore\packagesStore.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { ConfigType, PackagesStoreType, PackagesType } from './packagesStore.d'
import { packagesList } from '@/packages/index'
import { StorageEnum } from '@/enums/storageEnum'
import { getLocalStorage, setLocalStorage, getCustomizeList, deepClone } from '@/utils'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import {
  moduleGetList,
  moduleCreate,
  moduleDelete,
  moduleUpdate,
  templateCreate,
  templateGetList,
  templateDelete,
  templateUpdate,
  templateGet
} from 'swagger-api/export-api/scada-config'
import { ElMessage, ElMessageBox } from 'element-plus'
const StoreKeys = StorageEnum.GO_USER_MEDIA_CUSTOMIZE
const StoreTempKeys = StorageEnum.GO_USER_MEDIA_TEMP
// 组件 packages
export const usePackagesStore = defineStore({
  id: 'usePackagesStore',
  state: (): PackagesStoreType => ({
    packagesList: Object.freeze(packagesList),
    newPhoto: undefined,
    isCustomize: false, // 是否编辑自定义组件
    editCustomizeData: {}, //新建/编辑自定义组件
    componentList: [], // 原本组件列表
    isTemp: false // 是否模板编辑状态
  }),
  getters: {
    getPackagesList(): PackagesType {
      return this.packagesList
    },
    getComponentList(): PackagesType {
      return this.componentList
    }
  },
  actions: {
    addPhotos(newPhoto: ConfigType, index: number) {
      this.newPhoto = newPhoto
      this.packagesList.Photos?.splice(index, 0, newPhoto)
    },
    deletePhotos(photoInfo: ConfigType, index: number) {
      this.packagesList.Photos?.splice(index, 1)
      const StoreKey = StorageEnum.GO_USER_MEDIA_PHOTOS
      const userPhotosList = getLocalStorage(StoreKey)
      userPhotosList?.splice(index - 1, 1)
      setLocalStorage(StoreKey, userPhotosList)
    },
    addPrivate(newPhoto: ConfigType, index: number) {
      this.newPhoto = newPhoto
      this.packagesList.Informations?.splice(index, 0, newPhoto)
    },
    async deleteCustomize(item: ConfigType, index: number, isTemp: boolean) {
      const res = await (isTemp ? templateDelete(item.delId) : moduleDelete(item.delId))
      if (res.code == 0) {
        ElMessage({
          message: '操作成功！',
          type: 'success',
          duration: 2000
        })
        getCustomizeList(isTemp)
      }
    },
    //获取组件数据

    setGroup() {
      const chartEditStore = useChartEditStore()
      const { id, name } = this.editCustomizeData
      const list = deepClone(chartEditStore.getComponentList)
      const ids = list?.map((item: any) => item.id)
      let newGroup = {
        groupList: list,
        name,
        id,
        chartConfig: { image: '' }
      }
      !this.isTemp && ids?.length && (newGroup = chartEditStore.setGroup(ids, false, name))
      return { newGroup, isPass: ids?.length > 1 }
    },
    //设置编辑状态
    async setCustomize(isCustomize: boolean, item?: object, newGroup?: object) {
      const chartEditStore = useChartEditStore()
      item && (this.editCustomizeData = item)
      const { delId, name = '', groupList = [], children = [] } = this.editCustomizeData
      // 开始编辑 标识编辑状态
      if (isCustomize) {
        this.isCustomize = true
        try {
          let list = chartEditStore.getComponentList
          this.componentList = deepClone(list)
          chartEditStore.clearComponentList()
          if (delId) {
            if (this.isTemp) {
              const res = await templateGet(delId)
              if (res.code == 0) {
                //删除画布上其他的组件。
                chartEditStore.clearComponentList()
                const { config = {} } = res.data
                const { groupList = [] } = JSON.parse(config) || { groupList: [] }
                chartEditStore.setInitComponents(groupList)
              }
            } else {
              chartEditStore.setInitComponents(groupList)
            }
          }
          ElMessage({
            message: `进入编辑模式，您可以编辑${this.isTemp ? '模板' : '组件'}啦！`,
            type: 'success',
            duration: 3000
          })
        } catch (e) {
          this.componentList = []
        }
      } else {
        if (newGroup) {
          const o = newGroup
          o.category = this.isTemp ? 'Temp' : 'Customize'
          o.package = this.isTemp ? 'Temp' : 'Customize'
          const query = {
            config: JSON.stringify(o),
            imageUrl: newGroup.chartConfig.image,
            name
          }
          console.log(o, '提交的数据')
          if (this.isTemp) {
            await (delId ? templateUpdate(delId, query) : templateCreate(query))
            chartEditStore.clearComponentList()
          } else {
            await (delId ? moduleUpdate(delId, query) : moduleCreate(query))
          }
          getCustomizeList(this.isTemp)
        }
        //还原画布原来的内容。
        chartEditStore.setInitComponents(this.componentList)

        this.editCustomizeData = undefined
        this.isTemp = false
        this.isCustomize = false
        this.componentList = []
      }
    },
    //设置模板编辑
    setTemp(temp: boolean, item?: object, newGroup?: object) {
      this.isTemp = true
      this.setCustomize(temp, item, newGroup)
    },
    //取消编辑
    cancelEdit() {
      const chartEditStore = useChartEditStore()
      chartEditStore.clearComponentList()
      chartEditStore.setInitComponents(this.componentList)

      this.editCustomizeData = undefined
      this.isTemp = false
      this.isCustomize = false
      this.componentList = []
    }
  }
})
